package module.map.operations.propertys
{
	import drongo.model.core.IValue;
	import drongo.model.propertys.ArrayProperty;
	import drongo.model.values.CollectionValue;
	
	import common.operations.BaseOperation;
	
	import module.map.model.Propertys;
	import module.map.operations.propertys.datas.ArrayPropertyChangeData;
	import module.map.operations.propertys.datas.PropertyChangeData;
	
	/**
	 * 列表类数据修改
	 */
	public class ArrayPropertyChangedOperation extends BaseOperation
	{
		private var oldState:uint;
		private var parent:ArrayProperty;
		private var newPropertys:Vector.<ArrayPropertyChangeData>;
		private var oldPropertys:Vector.<ArrayPropertyChangeData>;
		public function ArrayPropertyChangedOperation()
		{
			super();
		}
		
		override public function destroy():void
		{
			
		}
		
		override public function execute():void
		{
			this.parent=this.data.parent;
			this.newPropertys=this.data.newPropertys;
			this.oldPropertys=this.data.oldPropertys;
			if(this.parent==null){
				throw new Error("数据父级不存在！");
			}
			if(this.newPropertys==null||this.newPropertys.length==0){
				throw new Error("新属性不能为空！");
			}
		
			this.oldState=this.project.currentMap.Get(Propertys.STATE).GetValue();
			this.SetPropertys(this.newPropertys);
			this.project.currentMap.Update(Propertys.STATE,1);
			
			if(this.oldPropertys!=null&&this.oldPropertys.length!=0){
				this.project.currentMap.recorder.link(this);
			}
		}
		
		private function SetPropertys(datas:Vector.<ArrayPropertyChangeData>):void{
			var changeData:ArrayPropertyChangeData;
			var child:IValue;
			for (var i:int = 0; i < datas.length; i++) 
			{
				changeData=datas[i];
				child=this.parent.GetChildByKeyAndValue(changeData.key,changeData.value);
				if(child is CollectionValue){
					for each (var property:PropertyChangeData in changeData.propertys) 
					{
						CollectionValue(child).Update(property.key,property.value);
					}
				}else{
					throw new Error("未处理的属性更新");
				}
			}
		}
		
		override public function redo():void
		{
			this.oldState=this.project.currentMap.Get(Propertys.STATE).GetValue();
			this.project.currentMap.Update(Propertys.STATE,1);
			this.SetPropertys(this.newPropertys);
		}
		
		override public function undo():void
		{
			var state:uint=this.project.currentMap.Get(Propertys.STATE).GetValue();
			if(state==0){
				this.project.currentMap.Update(Propertys.STATE,1);
			}else{
				this.project.currentMap.Update(Propertys.STATE,this.oldState);
			}
			this.SetPropertys(this.oldPropertys);
		}
	}
}